package com.future.mvc.web.json;

import com.future.mvc.web.json.entity.Dog;
import com.future.mvc.web.json.entity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <P>
 *
 * </p>
 *
 * @author yinhao
 * @version 1.0
 * @since 2024/9/7 19:19
 */
@RestController
public class JsonHandler {

    /**
     * 目标方法@ResponseBody, 表示返回的数据是json格式
     * springmvc底层会将返回的数据转换为json格式
     * 使用转换器
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/json/dog")
    public Dog getJson() {
        Dog dog = new Dog();
        dog.setName("小黑");
        dog.setAddress("北京");
        return dog;
    }

    @ResponseBody
    @RequestMapping("/json/dogs")
    public List<Dog> getJsons() {
        Dog dog = new Dog();
        dog.setName("小黑");
        dog.setAddress("北京");

        Dog dog1 = new Dog();
        dog1.setName("小白");
        dog1.setAddress("上海");

        List<Dog> dogs = new ArrayList<>();
        dogs.add(dog);
        dogs.add(dog1);
        return dogs;
    }

    @ResponseBody
    @RequestMapping("/save2")
    public User saveUser(@RequestBody User user) {
        System.out.println("user=" + user);
        return user;
    }

    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws Exception {

        InputStream inputStream = session.getServletContext().getResourceAsStream("/img/Snipaste_2023-04-26_00-46-23.png");

        // 开辟一个存放文件的字节数组,使用byte数组是因为可以支持二进制数据
        byte[] bytes = new byte[inputStream.available()];
        // 数据读入byte数组
        inputStream.read(bytes);

        // public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status)
        // 创建返回的HttpStatus状态码
        HttpStatus status = HttpStatus.OK;
        // 创建headers
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=Snipaste_2023-04-26_00-46-23.png");
        return new ResponseEntity<>(bytes, headers, status);
    }

    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file,String introduce, HttpServletRequest req) throws Exception {
        System.out.println("introduce=" + introduce);
        String fileName = file.getOriginalFilename();
        String fileFullPath = req.getServletContext().getRealPath("/img/" + fileName);
        file.transferTo(new File(fileFullPath));
        return "success";
    }
}
